﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace Avivo.Common
{
	public class Utils
	{
		/// <summary>
		/// Reads a stream into string.
		/// </summary>
		/// <param name="stream">Readable stream.</param>
		/// <returns>Returns a UTF8 encoded string.</returns>
		public static string ReadStream(Stream stream)
		{
			long length;
			return ReadStream(stream, 4096, out length, null);
		}

		/// <summary>
		/// Reads a stream into string.
		/// </summary>
		/// <param name="stream">Readable stream.</param>
		/// <param name="bufferSize">Size of a read buffer in bytes.</param>
		/// <param name="readLength">[out] Total number of bytes read.</param>
		/// <param name="callback">Callback method to report progress change.</param>
		/// <returns>Returns a UTF8 encoded string.</returns>
		public static string ReadStream(Stream stream, int bufferSize, out long readLength, Action<long, long> callback)
		{
			readLength = 0;
			string result = null;
			if (stream != null && stream.CanRead)
			{
				int length = 0;
				byte[] buffer = new byte[bufferSize];
				StringBuilder builder = new StringBuilder();
				while ((length = stream.Read(buffer, 0, bufferSize)) > 0)
				{
					builder.Append(Encoding.UTF8.GetString(buffer, 0, length));
					readLength += length;
					if (callback != null)
					{
						callback(readLength, stream.Length);
					}
				}
				result = builder.ToString();
			}
			return result;
		}

		/// <summary>
		/// Generates a MD5 hash of a string.
		/// </summary>
		/// <param name="strToHash">String to encode.</param>
		/// <returns>Returns lowercase encoded string.</returns>
		public static string CreateMD5(string input)
		{
			MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
			byte[] bytes = Encoding.ASCII.GetBytes(input);
			bytes = md5.ComputeHash(bytes);
			string result = null;
			foreach (byte b in bytes)
			{
				result += b.ToString("x2");
			}
			return result;
		}
	}
}
